import React, { Component } from 'react';
import PropTypes from "prop-types";
import Label from '../label/index';
import {
    View,
    Image,
    StyleSheet,
    Animated,
    TouchableWithoutFeedback,
    Alert,
    Text,
    Modal,
    Dimensions,
    TouchableOpacity
} from 'react-native';


const STEP_STATUS = {
    CURRENT: 'current',
    FINISHED: 'finished',
    UNFINISHED: 'unfinished'
};
const customStyles = {
    //为未选中的图标大小
    stepIndicatorSize: PropTypes.number,
    //选中的图标大小
    currentStepIndicatorSize: PropTypes.number,
    //连接线的宽度
    separatorStrokeWidth: PropTypes.number,
    //选中之后圆圈数字之后的背景
    stepStrokeWidth: PropTypes.number,
    //圆环的厚度
    currentStepStrokeWidth: PropTypes.number,
    //圆环的颜色
    stepStrokeCurrentColor: PropTypes.string,
    stepStrokeFinishedColor: PropTypes.string,
    stepStrokeUnFinishedColor: PropTypes.string,
    //已经过了的线的颜色
    separatorFinishedColor: PropTypes.string,
    //未过了的线的颜色
    separatorUnFinishedColor: PropTypes.string,
    //已经过了的圆圈颜色
    stepIndicatorFinishedColor: PropTypes.string,
    //未过的圆圈颜色
    stepIndicatorUnFinishedColor: PropTypes.string,
    //当前圆环内部的颜色
    stepIndicatorCurrentColor: PropTypes.string,
    //未选中的圆圈文字大小
    stepIndicatorLabelFontSize: PropTypes.number,
    //当前选中文字的大小
    currentStepIndicatorLabelFontSize: PropTypes.number,
    //当前的选中的颜色
    stepIndicatorLabelCurrentColor: PropTypes.string,
    //已经完成的步骤的字体颜色
    stepIndicatorLabelFinishedColor: PropTypes.string,
    //未完成的步骤的字体颜色
    stepIndicatorLabelUnFinishedColor: PropTypes.string,
    //错误节点颜色
    errorStepColor: PropTypes.string,
    //非选中的下面的字体的颜色
    labelColor: PropTypes.string,
    //当前选中的下面的字体颜色
    currentStepLabelColor: PropTypes.string,
    //label的字体大小
    labelSize: PropTypes.number,
    //线段是否到左边
    isToLeft: PropTypes.bool,
    //文字区域样式
    labelContainerStyle: PropTypes.any,
    //非选中的提示文本字体颜色
    minorLabelColor: PropTypes.string,
    //当前选中的提示文本字体颜色
    currentMinorLabelColor: PropTypes.string,
    //label的字体大小
    minorLabelSize: PropTypes.number,
};
const { width } = Dimensions.get('window')
export default class Step extends Component {

    constructor(props) {
        super(props);
        this.state = {
            width: 198,
            height: 0,
            progressBarSize: 0,
            nodePosition: '',
            nodeStyle: false,
            Modalheight: 300
        };

        const defaultStyles = {
            stepIndicatorSize: 20,
            currentStepIndicatorSize: 20,
            separatorStrokeWidth: 2,
            currentStepStrokeWidth: 5,
            stepStrokeWidth: 0,
            stepStrokeCurrentColor: '#FA5050',//red current border      当前选中的外圆环
            separatorFinishedColor: '#666666',//grey line
            separatorUnFinishedColor: '#D8D8D8',//grey line
            stepIndicatorFinishedColor: '#666666',//red finish background    已完成的中心圆圈
            stepIndicatorUnFinishedColor: '#D8D8D8',//grey unfinished background
            stepIndicatorCurrentColor: '#FA5050',//red current background            
            stepStrokeFinishedColor: '#666666',//red finshed border
            stepStrokeUnFinishedColor: '#D8D8D8',//grey unfinished border
            stepIndicatorLabelFontSize: 13,
            currentStepIndicatorLabelFontSize: 13,
            stepIndicatorLabelCurrentColor: '#FFFFFF',//red current font
            stepIndicatorLabelFinishedColor: '#FFFFFF',//red finshed font
            stepIndicatorLabelUnFinishedColor: '#ffffff',//grey unfinished font
            labelColor: '#333333',//!current majorLabel 
            labelSize: 13,
            currentStepLabelColor: '#333333',//current majorLabel 
            errorStepColor: '#FA5050',
            isToLeft: false,
            // 未选中的提示文本颜色
            minorLabelColor: '#666666', //!current minorLabel 
            // 当前选中的提示文本字体颜色
            currentMinorLabelColor: '#666666', //current minorLabel 
            // label的字体大小
            minorLabelSize: 12,
        };

        this.customStyles = Object.assign(defaultStyles, props.customStyles);
        this.progressAnim = new Animated.Value(0);
        this.sizeAnim = new Animated.Value(this.customStyles.stepIndicatorSize);
        this.borderRadiusAnim = new Animated.Value(this.customStyles.stepIndicatorSize / 2);
    }

    stepPressed(position) {
        if (this.props.onPress) {
            this.props.onPress(position)
        }
    }

    setNodeStyle(position) {//点击事件
        if (this.state.nodePosition != position && this.state.nodeStyle == true) {
            alert('只有一个节点可修改为错误样式，单击取消样式修改');
        } else {
            Alert.alert('', '确认修改此节点样式？',
                [{
                    text: 'OK', onPress: () => {
                        this.setState({
                            nodePosition: position,
                            nodeStyle: !this.state.nodeStyle
                        });
                    }
                },
                { text: 'cancel', style: 'cancel' }]);
        }

    }

    openmodal = () => {
        this.setState({
            Modalheight: 20
        })
    }
    closemodal = () => {
        this.setState({
            Modalheight: 300
        })
    }
    render() {
        const { labels, direction, order } = this.props;
        return (
            <View style={[styles.container, direction === 'vertical' ? { flexDirection: 'row', flex: 1 } : { flexDirection: 'column' }]}>
                {direction === 'vertical' ? this.time() : null}
                {this.state.width !== 0 && this.renderProgressBarBackground()}
                {this.state.width !== 0 && this.renderProgressBar()}
                {/* 圆 */}
                {this.renderStepIndicator()}
                {/* 字体 */}
                {labels && this.renderStepLabels()}
            </View>
        );
    }

    componentDidUpdate(prevProps) {
        if (this.props.currentPosition !== prevProps.currentPosition) {
            this.onCurrentPositionChanged(this.props.currentPosition, this.props.direction);
        }
    }
    

    // 左侧文字样式
    time = () => {
        const { labels, direction, order } = this.props;

        let list = labels;
        let labelViews = list.map((label, index) => {
            return <Label text={label.leftTime} labelStyle={styles.leftTime} />
        });
        return (
            <View style={[styles.stepLabelsContainer,
            direction === 'vertical' ?
                { flexDirection: 'column', paddingHorizontal: 4, alignItems: 'flex-start' } :
                { flexDirection: 'row', paddingVertical: 4, alignItems: 'center' }]}>
                {labelViews}
            </View>
        )
    }
    //未完成灰线
    renderProgressBarBackground = () => {
        const { stepCount, direction, isShowHalf } = this.props;
        let leftIsShowHalf = Math.floor(stepCount / 2);  
        let progressBarBackgroundStyle;
        if (direction === 'vertical') {
            progressBarBackgroundStyle = {
                backgroundColor: this.customStyles.separatorUnFinishedColor,
                position: 'absolute',
                left: 99,
                top: this.state.height / (2 * stepCount),
                bottom: this.state.height / (2 * stepCount),
                width: this.customStyles.separatorStrokeWidth
            }
        }
        else {
            progressBarBackgroundStyle = {
                backgroundColor: this.customStyles.separatorUnFinishedColor,  // 未过选中线的颜色
                position: 'absolute',
                top: (this.state.height - this.customStyles.separatorStrokeWidth) / 2,
                left: !this.customStyles.isToLeft ? isShowHalf ? this.state.width / (2 * (stepCount - leftIsShowHalf)) : this.state.width / (2 * stepCount) : 0,
                right: !this.customStyles.isToLeft ? isShowHalf ? this.state.width / (2 * (stepCount - leftIsShowHalf)) : this.state.width / (2 * stepCount) : 0,
                height: this.customStyles.separatorStrokeWidth
            }
        }
        return (
            <View
                onLayout={(event) => {
                    if (direction === 'vertical') {
                        this.setState({ progressBarSize: event.nativeEvent.layout.height }, () => { this.onCurrentPositionChanged(this.props.currentPosition, direction) })
                    }
                    else {
                        this.setState({ progressBarSize: event.nativeEvent.layout.width }, () => { this.onCurrentPositionChanged(this.props.currentPosition, direction) })
                    }
                }}
                style={progressBarBackgroundStyle} />
        )
    };


    //已完成步骤的线
    renderProgressBar = () => {
        const { stepCount, direction, isShowHalf } = this.props;
        let leftIsShowHalf = Math.floor(stepCount / 2);
        let progressBarStyle;
        if (direction === 'vertical') {
            progressBarStyle = {
                backgroundColor: this.customStyles.separatorFinishedColor,
                position: 'absolute',
                left: 99,
                top: this.state.height / (2 * stepCount),
                bottom: this.state.height / (2 * stepCount),
                width: this.customStyles.separatorStrokeWidth,
                height: this.progressAnim
            }
        }
        else {
            progressBarStyle = {
                backgroundColor: this.customStyles.separatorFinishedColor,
                position: 'absolute',
                top: (this.state.height - this.customStyles.separatorStrokeWidth) / 2,
                left: isShowHalf ? this.state.width / (2 * (stepCount - leftIsShowHalf)) : this.state.width / (2 * stepCount),
                right: isShowHalf ? this.state.width / (2 * (stepCount - leftIsShowHalf)) : this.state.width / (2 * stepCount),
                height: this.customStyles.separatorStrokeWidth,
                width: this.progressAnim
            }
        }
        return (
            <Animated.View
                style={progressBarStyle} />
        )
    };

    //圆圈
    renderStepIndicator = () => {
        let steps = [];
        const { labels, stepCount, direction, isShowHalf, isShowClick } = this.props;
        if (direction == 'horizontal') {

            if (stepCount == 2 || 3 || 4 || 5) {
                for (let position = 0; position < stepCount; isShowHalf ? position += 2 : position++) {
                    steps.push(
                        isShowClick ?
                            <TouchableWithoutFeedback key={position} onPress={() => this.setNodeStyle(position)}>
                                <View style={[styles.stepContainer, direction === 'vertical' ? { flexDirection: 'column' } : { flexDirection: 'row' }]}>
                                    {this.renderStep(position)}
                                </View>
                            </TouchableWithoutFeedback>
                            :
                            <TouchableWithoutFeedback key={position}>
                                <View style={[styles.stepContainer, direction === 'vertical' ? { flexDirection: 'column' } : { flexDirection: 'row' }]}>
                                    {this.renderStep(position)}
                                </View>
                            </TouchableWithoutFeedback>
                    )
                }
            } else {
                steps.push(<Label text='节点数量有误' />)
            }

        } else {
            for (let position = 0; position < stepCount; isShowHalf ? position += 2 : position++) {
                steps.push(
                    isShowClick ?
                        <TouchableWithoutFeedback key={position} onPress={() => this.setNodeStyle(position)}>
                            <View style={[styles.stepContainer, direction === 'vertical' ? { flexDirection: 'column' } : { flexDirection: 'row' }]}>
                                {this.renderStep(position)}
                            </View>
                        </TouchableWithoutFeedback>
                        :
                        <TouchableWithoutFeedback key={position}>
                            <View style={[styles.stepContainer, direction === 'vertical' ? { flexDirection: 'column' } : { flexDirection: 'row' }]}>
                                {this.renderStep(position)}
                            </View>
                        </TouchableWithoutFeedback>
                )
            }
        }


        return (
            <View onLayout={(event) => this.setState({ width: event.nativeEvent.layout.width, height: event.nativeEvent.layout.height })}
                style={[styles.stepIndicatorContainer, direction === 'vertical' ? { flexDirection: 'column', width: this.customStyles.currentStepIndicatorSize } :
                    { flexDirection: 'row', height: this.customStyles.currentStepIndicatorSize }]}>
                {steps}
            </View>
        )
    };

    //文字
    renderStepLabels = () => {
        const { labels, direction, currentPosition, stepCount, order } = this.props;
        const itemHeight = (this.state.progressBarSize / (stepCount - 1));
        const horizontalLabelStyle = direction === 'vertical' ? {} : { flex: 1, paddingTop: 0, height: 'auto' };
        let list = labels;
        if (order == 'desc' && this.state.nodePosition === '') {
            list = labels.reverse();
        }
        let labelViews = list.map((label, index) => {

            const selectedStepLabelStyle = index === currentPosition ? { color: this.customStyles.currentStepLabelColor } : { color: this.customStyles.labelColor };

            const stepLabelContainerStyle = index === currentPosition ? { paddingTop: (itemHeight - this.customStyles.currentStepIndicatorSize) / 2 } : { paddingTop: (itemHeight - this.customStyles.stepIndicatorSize) / 2 };
            let minorLabel = label.minorLabel ?
                <Label text={label.minorLabel}
                    numberOfLines={2}
                    labelStyle={[styles.stepLabel, { fontSize: this.customStyles.minorLabelSize, color: index == currentPosition ? this.customStyles.currentMinorLabelColor : this.customStyles.minorLabelColor }]} /> : null;

            if (label.minorLabel != null && (label.minorLabel).length > 14) {

                let mes = '字符过长无法显示';
                return (
                    <TouchableWithoutFeedback key={index} onPress={() => this.stepPressed(index)}>
                        <View style={[direction === 'vertical' ? { alignItems: 'flex-start' } : { alignItems: 'center' }, { width: 242 }, this.customStyles.labelContainerStyle, stepLabelContainerStyle, { height: itemHeight }, horizontalLabelStyle]}>

                            <View style={{ height: index === currentPosition ? this.customStyles.currentStepIndicatorSize : this.customStyles.stepIndicatorSize, justifyContent: 'center' }}>
                                <Label text={label.majorLabel} labelStyle={[styles.stepLabel, selectedStepLabelStyle, { fontSize: this.customStyles.labelSize }]} />
                            </View>
                            <Label text={mes} labelStyle={[styles.stepLabel, selectedStepLabelStyle, { fontSize: this.customStyles.labelSize }]} />
                        </View>
                    </TouchableWithoutFeedback>
                )
            } else {
                return (
                    <TouchableWithoutFeedback key={index} onPress={() => this.stepPressed(index)}>
                        <View style={[direction === 'vertical' ? { alignItems: 'flex-start' } : { alignItems: 'center' }, { width: 242 }, this.customStyles.labelContainerStyle, stepLabelContainerStyle, { height: itemHeight }, horizontalLabelStyle]}>
                            <View style={{ height: index === currentPosition ? this.customStyles.currentStepIndicatorSize : this.customStyles.stepIndicatorSize, justifyContent: 'center' }}>
                                <Label text={label.majorLabel} labelStyle={[styles.stepLabel, selectedStepLabelStyle, { fontSize: this.customStyles.labelSize }]} />
                            </View>
                            {minorLabel}
                        </View>
                    </TouchableWithoutFeedback>
                )
            }

        });

        return (
            <View style={[styles.stepLabelsContainer,
            direction === 'vertical' ?
                { flexDirection: 'column', paddingHorizontal: 4, alignItems: 'flex-start' } :
                { flexDirection: 'row', paddingVertical: 4, alignItems: 'center' }]}>
                {labelViews}
            </View>
        )
    };

    renderStep = (position) => {
        const { currentPosition, stepCount, direction, orderStyle, imgPath, imgStyle } = this.props;
        let stepStyle;
        let indicatorLabelStyle;
        const separatorStyle = (direction === 'vertical') ? { width: this.customStyles.separatorStrokeWidth, zIndex: 10 } : { height: this.customStyles.separatorStrokeWidth }
        switch (this.getStepStatus(position)) {
            case STEP_STATUS.CURRENT: {
                if (position == this.state.nodePosition && this.state.nodeStyle == true) {
                    stepStyle = {
                        backgroundColor: this.customStyles.stepIndicatorCurrentColor,
                        borderWidth: this.customStyles.errorStepColor,
                        height: this.sizeAnim,
                        width: this.sizeAnim,
                        borderRadius: this.borderRadiusAnim
                    };
                } else {
                    stepStyle = {
                        backgroundColor: this.customStyles.stepIndicatorCurrentColor,
                        borderWidth: this.customStyles.currentStepStrokeWidth,
                        borderColor: this.customStyles.stepStrokeCurrentColor,
                        height: this.sizeAnim,
                        width: this.sizeAnim,
                        borderRadius: this.borderRadiusAnim
                    };
                }
                indicatorLabelStyle = { fontSize: this.customStyles.currentStepIndicatorLabelFontSize, color: this.customStyles.stepIndicatorLabelCurrentColor, height: this.customStyles.stepIndicatorSize, lineHeight: this.customStyles.stepIndicatorSize };
                break;
            }
            case STEP_STATUS.FINISHED: {
                if (position == this.state.nodePosition && this.state.nodeStyle == true) {
                    stepStyle = {
                        backgroundColor: this.customStyles.stepIndicatorFinishedColor,
                        borderWidth: this.customStyles.stepStrokeWidth,
                        borderColor: this.customStyles.errorStepColor,
                        height: this.customStyles.stepIndicatorSize,
                        width: this.customStyles.stepIndicatorSize,
                        borderRadius: (this.customStyles.stepIndicatorSize) / 2
                    };
                } else {
                    stepStyle = {
                        backgroundColor: this.customStyles.stepIndicatorFinishedColor,
                        borderWidth: this.customStyles.stepStrokeWidth,
                        borderColor: this.customStyles.stepStrokeFinishedColor,
                        height: this.customStyles.stepIndicatorSize,
                        width: this.customStyles.stepIndicatorSize,
                        borderRadius: (this.customStyles.stepIndicatorSize) / 2
                    };
                }
                indicatorLabelStyle = { fontSize: this.customStyles.stepIndicatorLabelFontSize, color: this.customStyles.stepIndicatorLabelUnFinishedColor, height: this.customStyles.stepIndicatorSize, lineHeight: this.customStyles.stepIndicatorSize };
                break;
            }

            case STEP_STATUS.UNFINISHED: {
                if (position == this.state.nodePosition && this.state.nodeStyle == true) {
                    stepStyle = {
                        backgroundColor: this.customStyles.stepIndicatorUnFinishedColor,
                        borderWidth: this.customStyles.stepStrokeWidth,
                        borderColor: this.customStyles.errorStepColor,
                        height: this.customStyles.stepIndicatorSize,
                        width: this.customStyles.stepIndicatorSize,
                        borderRadius: (this.customStyles.stepIndicatorSize) / 2
                    };
                } else {
                    stepStyle = {
                        backgroundColor: this.customStyles.stepIndicatorUnFinishedColor,
                        borderWidth: this.customStyles.stepStrokeWidth,
                        borderColor: this.customStyles.stepStrokeUnFinishedColor,
                        height: this.customStyles.stepIndicatorSize,
                        width: this.customStyles.stepIndicatorSize,
                        borderRadius: (this.customStyles.stepIndicatorSize) / 2
                    };
                }
                indicatorLabelStyle = { overflow: 'hidden', fontSize: this.customStyles.stepIndicatorLabelFontSize, color: this.customStyles.stepIndicatorLabelFinishedColor, height: this.customStyles.stepIndicatorSize, lineHeight: this.customStyles.stepIndicatorSize };
                break;
            }
            default:
        }
        if (orderStyle == 'pic') {
            return (

                <Animated.View key={'step-indicator'} removeClippedSubviews style={[styles.step, stepStyle]}>
                    <Image
                        source={imgPath}
                        style={imgStyle} />
                </Animated.View>
            );
        } else {
            return (

                <Animated.View key={'step-indicator'} removeClippedSubviews style={[styles.step, stepStyle]}>
                    <Label text={position + 1 + ''} labelStyle={[indicatorLabelStyle]} />
                </Animated.View>
            );
        }

    };

    getStepStatus = (stepPosition) => {
        const { currentPosition } = this.props;
        if (stepPosition === currentPosition) {
            return STEP_STATUS.CURRENT;
        }
        else if (stepPosition < currentPosition) {
            return STEP_STATUS.FINISHED;
        }
        else {
            return STEP_STATUS.UNFINISHED;
        }
    };
    // 半条线
    onCurrentPositionChanged = (position, direction) => {
        let { stepCount } = this.props;
        if (position > stepCount - 1) {
            position = stepCount - 1;
        } else if (position < stepCount - 1) {
            if (direction == 'vertical') {
                position += 0.5;
            } else {
                position += 0;
            }
        }
        const animateToPosition = (this.state.progressBarSize / (stepCount - 1)) * position;
        this.sizeAnim.setValue(this.customStyles.stepIndicatorSize);
        this.borderRadiusAnim.setValue(this.customStyles.stepIndicatorSize / 2);
        Animated.sequence([
            Animated.timing(
                this.progressAnim,
                { toValue: animateToPosition, duration: 200 }
            ),
            Animated.parallel([
                Animated.timing(
                    this.sizeAnim,
                    { toValue: this.customStyles.currentStepIndicatorSize, duration: 100 }
                ),
                Animated.timing(
                    this.borderRadiusAnim,
                    { toValue: this.customStyles.currentStepIndicatorSize / 2, duration: 100 }
                )
            ])
        ]).start();
    }
}
Step.propTypes = {
    currentPosition: PropTypes.number,
    stepCount: PropTypes.number,
    customStyles: PropTypes.object,
    direction: PropTypes.oneOf(['vertical', 'horizontal']),
    labels: PropTypes.array,
    order: PropTypes.string,
    orderStyle: PropTypes.string,
    onPress: PropTypes.func,
    isShowHalf: PropTypes.bool,
    //取消点击事件
    isShowClick: PropTypes.bool,
};

Step.defaultProps = {
    currentPosition: 0,
    stepCount: 5,
    customStyles: {},
    direction: 'horizontal',
    labels: [],
    order: '',
    orderStyle: '',
    isShowHalf: false,    //控制135步骤
    isShowClick: true
};
const styles = StyleSheet.create({
    container: {
        backgroundColor: 'transparent'
    },
    stepIndicatorContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-around',
        backgroundColor: 'transparent'
    },
    stepLabelsContainer: {
        justifyContent: 'space-around'
    },
    step: {
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 2
    },
    stepContainer: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    },
    stepLabel: {
        fontSize: 12,
        textAlign: 'center',
        fontWeight: '400'
    },
    stepLabelItem: {
        flex: 1,
    },
    leftbox: {
        height: 34,
        width: 82
    },
    leftTime: {
        fontSize: 12,
        color: '#666',
        fontWeight: '400',
        textAlign: 'right',
        width: 82,
        height: 34,
        fontFamily: 'PingFang SC',
        marginTop: 18
    },
    descmodal: {
        display: 'flex',
        justifyContent: 'flex-start',
        alignItems: 'center',
        width,
        backgroundColor: '#F4F4F4',
        position: 'absolute',
        //   zIndex:1,
        bottom: 0
    },
    openmodaltext: {
        alignItems: 'center',
        fontSize: 15,
        color: '#2E6CC6',
        // width,
        // height:80,
        backgroundColor: '#fff'
    }
});

